package com.cheer.security;

import com.cheer.dao.AccountDao;
import com.cheer.dao.AdminDao;
import com.cheer.dao.ApplicantDao;
import com.cheer.entity.Account;
import com.cheer.entity.Admin;
import com.cheer.entity.Applicant;
import com.cheer.enums.CaptchaEnum;
import com.cheer.enums.RoleEnum;
import com.cheer.enums.TitleEnum;
import com.cheer.vo.LoginVO;
import com.cheer.vo.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author cheer
 */
@Component
public class RestAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private UserInfoHolder userInfoHolder;

    @Autowired
    private ApplicantDao applicantDao;

    @Autowired
    private AdminDao adminDao;

    @Autowired
    private AccountDao accountDao;

    @Override
    public void onAuthenticationSuccess(
            HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException {

        Account account = userInfoHolder.getAccount();

        // 返回给前端的角色信息
        LoginVO loginVO = new LoginVO();
        loginVO.setRole(account.getRole());

        // 如果是集体角色，返回给前端是否可以编辑台账
        if (RoleEnum.APPLICANT.getCode() == account.getRole()) {
            Applicant applicant = applicantDao.getByAccountId(account.getId());
            if (applicant == null) {
                accountDao.deleteById(account.getId());
                response.sendRedirect("/auth/logout");
                return;
            }
            loginVO.setCityTitled(TitleEnum.CITY.getType() == applicant.getTitle());
        } else {
            Admin admin = adminDao.getByAccountId(account.getId());
            if (admin == null) {
                accountDao.deleteById(account.getId());
                response.sendRedirect("/auth/logout");
                return;
            }
            userInfoHolder.setAdminOrgId(admin.getOrgId());
        }

        // 删除登录验证码产生的 Session
        HttpSession session = request.getSession();
        session.removeAttribute(CaptchaEnum.LOGIN.getAttribute());
        session.removeAttribute(SecurityConfig.FAILED_LOGIN);

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(objectMapper.writeValueAsString(Result.success(loginVO)));
        response.getWriter().flush();
    }
}
